package Twitim::SessionManager;

use strict;
use warnings;


use Gtk2;

use Net::DBus::GLib;
use Net::DBus qw(:typing);

sub new {
    my $this  = shift;
    my $class = ref($this) || $this;
    my $self  = {@_};

    bless $self, $class;
}

sub connect {
    my $self = shift;

    my $bus     = Net::DBus::GLib->session;
    my $service = $bus->get_service('org.gnome.SessionManager');
    $self->{'session_manager'} = my $session_manager
        = $service->get_object( '/org/gnome/SessionManager',
        'org.gnome.SessionManager' );

    my $startup_id = $ENV{'DESKTOP_AUTOSTART_ID'} || "";
    $self->{'client_path'} = my $client_path
        = $session_manager->RegisterClient( 'Twitim', $startup_id );
    my $client_private = $service->get_object( $client_path,
        'org.gnome.SessionManager.ClientPrivate' );

    $client_private->connect_to_signal(
        'QueryEndSession',
        sub {
            print "yes\n";
            $client_private->EndSessionResponse( dbus_boolean(1),
                "Always OK" );
        }
    );

    $client_private->connect_to_signal(
        'EndSession',
        sub {
            $main::MAINWIN->quit(1);
            print "endsession\n";
            $client_private->EndSessionResponse( dbus_boolean(1),
                "Always OK" );
            # $session_manager->UnregisterClient($client_path);
            Gtk2->main_quit;
        }
    );

    $client_private->connect_to_signal(
        'Stop',
        sub {
            print "stop\n";
            # $session_manager->UnregisterClient($client_path);
        }
    );

}

sub disconnect {
    my $self = shift;
    $self->{'session_manager'}->UnregisterClient( $self->{'client_path'} );
    print "disconnect!!\n";
}

sub end_session_response {
    my ( $self, $is_ok, $message ) = @_;
    $is_ok   ||= 1;
    $message ||= "";

    #$client_private->EndSessionResponse( dbus_boolean($is_ok), "$message" );
}

1;
